/*  Prolific  (c) 2011 Digital Planets  ALL RIGHTS RESERVED */

/*  Note: this is NOT open source code.  It is propriatary and owned by the copywright holder. */

/* DO NOT SHARE OR DISTRUBUTE */

/*******  Helper  functions   **********/
 if (!Array.prototype.forEach) {    Array.prototype.forEach = function(fun)  {     for (var i = 0; i < this.length; i  )  {     fun.call(null,this[i]);     }  }  }
 $id = function(id) { return document.getElementById(id) }
 $get = function(id) { return document.getElementById(id).value }
 $ce = function(type, parent) { var o = document.createElement(type); parent.appendChild(o); return o }
 $set = function(id, html) { $id(id).innerHTML = html }
 $toggle = function(id) { $id(id).style.visibility = ($id(id).style.visibility == 'hidden') ? '':'hidden' }
 String.prototype.fmt = function(arr) { var s = this.valueOf(); arr.forEach(function(a){s=s.replace('{}',a)}); return s; }


 if(!window['log']) log = function(t) {  if(window["console"]) console.log(t) }

/*******  The prolific object and config   **********/
var prolific = {};  prolific.yettoload = "";    
prolific.config = {
	"path" : "http://projs.info/api/",
	"tags" : "div",
	"rpcpath" : "http://projs.info/api/rpc.php",
	"alias" : {
		jquery : "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js",
		jqueryui : "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js",
		jqueryui_css : "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/themes/base/jquery-ui.css"
	}
};

/*******  This runs first   **********/
function init() {
   if(document.readyState != 'complete' && this.readyState != 'loaded') return setTimeout(arguments.callee, 20);
   prolific.load(prolific.config.path + 'controls.js', prolific.process);
}

log("Starting Prolific");
//init();


/*******  prolific.process   **********/
prolific.process = function() {
           var es = document.getElementsByTagName(prolific.config.tags); 
           var ctls = [];
           // Do requires
           for(var i=0;i<es.length;i  ) { 
                 if(es[i].getAttribute("control")) ctls.push(es[i]);
                 if(r = es[i].getAttribute("requires")) prolific.dorequires(r);    
           }

           for(var i=0;i<ctls.length;i  ) { 
                 log("to process: "  +   ctls[i].outerHTML);
           }

         (function() {
              if(prolific.yettoload.length != 0) return setTimeout(arguments.callee, 20);
              for(var i=0;i<ctls.length;i  ) { 
                  var e = ctls[i];
                  log("Processing "  +   e.id);
                  var f = e.getAttribute('control');
                  var dev = e.getAttribute('device');
                  if(dev && !navigator.userAgent.match(dev)) continue;

                  var p = e.getAttribute("params") || ""; 
                  var o = eval("{}({})".fmt([f, p]));
                  switch(typeof o)  {
                                       case "string":     e.innerHTML = o; break;
                                       case "object":    if(o.domelement) e.appendChild(o.domelement);
                   }
                   if(e.id) window[e.id] = o;
               }
            })();
}

/*******  prolific.dorequires   **********/
prolific.dorequires = function (items) {
      items.split(",").forEach(function(item) { 
          log("loading "  +  item);  var url = prolific.config.alias[item];
          if(!(/css$/.test(url))) prolific.yettoload  = item;
          prolific.load(url, (function() { prolific.yettoload = prolific.yettoload.replace(item, ''); 
		  log('pytl: ' +  prolific.yettoload) }));
      });
}


/*******  prolific.load  ***********/
prolific.load = function(url, cb) { 
                     if(/css$/.test(url)) { 
                          var e = document.createElement("link");  e.href = url;  e.rel = "stylesheet";
                     } else {  
                          var e = document.createElement("script");  e.src = url;  type = 'text/javascript';
                     }
                     e.onload = cb;
                     e.onreadystatechange = function() {
	          if (e.readyState == 'complete' || e.readyState == 'loaded') cb();
                     }
                     document.getElementsByTagName("head")[0].appendChild(e);
}

/*******  prolific.rpc  ***********/
/*  call like this:    prolific.rpc("gettime")();
    or like this:       var p = prolific.rpc("gettime");   p();
*/

prolific.rpc = function(fn) {
	return function(o) { 	
	   var p="";     
	   for(i in o) {   p  += ("&" + i + "=" + escape(o[i]));    } 
			var q = "f={}{}".fmt([fn, p]);
			alert(q);

			if(q.length < 300) {
			 var resp = prolific.get(prolific.config.rpcpath +  "?" +  q);  
			} else {
			 log("POST: " + prolific.config.rpcpath + "?" + q);
			 var resp = prolific.post(prolific.config.rpcpath, q);
			 log("RESPONSE: "+ resp);	
			}
			return resp;
	}
}

/*******  prolific.get, post  ***********/
prolific.get = function(u) {  var x=new XMLHttpRequest();   x.open('GET', u, false);  x.send();  return x.responseText  }
prolific.post = function(u, data) {  var x=new XMLHttpRequest();   x.open('POST', u, false);  
	x.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
	x.send(data);  return x.responseText  }
